/*
 * BanBu_addTongxunluController
 * @description 本文件提供通讯录列表的ViewController
 * @package
 * @author 		yinlinlin
 * @copyright
 * @version 		***
 * @description 本文件提供通讯录列表的ViewController
 */

#import "BanBu_addTongxunluController.h"
#import "BanBu_addTongxunluCell.h"
@interface BanBu_addTongxunluController ()

@end

@implementation BanBu_addTongxunluController

#define addressNameKey @"addressPeopleName"

- (void)dealloc
{
    [_addressTable release];
    _addressTable = nil;
    [_iphoneList release];
    _iphoneList = nil;
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = NSLocalizedString(@"add_tongxunlu", nil);
    _iphoneList = [[NSMutableArray alloc]initWithCapacity:10];
    _addressTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height - 44) style:UITableViewStylePlain];
    _addressTable.dataSource = self;
    _addressTable.delegate = self;
    [self.view addSubview:_addressTable];
    self.view.backgroundColor = UIColorWithRGB(242, 243, 232, 1.0);
    _addressTable.backgroundColor = UIColorWithRGB(242, 243, 232, 1.0);

    _addressTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self ReadAllPeoples];
}
#pragma mark - 获取通信录
/**
 * @函数名称：ReadAllPeoples
 * @函数描述：获取本机的通讯录
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
-(void)ReadAllPeoples
{    //取得本地通信录名柄
    
    ABAddressBookRef tmpAddressBook = nil;
    
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        tmpAddressBook=ABAddressBookCreateWithOptions(NULL, NULL);
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(tmpAddressBook, ^(bool greanted, CFErrorRef error){
            dispatch_semaphore_signal(sema);
        });
        
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }
    //取得本地所有联系人记录
    if (tmpAddressBook==nil) {
        return ;
    };
    NSArray* tmpPeoples = (__bridge NSArray*)ABAddressBookCopyArrayOfAllPeople(tmpAddressBook);
    for(id tmpPerson in tmpPeoples)
    {
        NSMutableDictionary * peopleDict = [NSMutableDictionary dictionary];
//        ABRecordRef person = CFArrayGetValueAtIndex(results, i);
        //获取的联系人单一属性:First name
        NSString* tmpFirstName = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonFirstNameProperty);;
        //获取的联系人单一属性:Last name
        NSString* tmpLastName = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonLastNameProperty);
        NSMutableString * nameStr = [NSMutableString string];
        //汉语
        NSString *langauage=[MyAppDataManager getPreferredLanguage];
        if([langauage isEqual:@"zh-Hans"])
        {
            if (tmpLastName)
            {
                [nameStr appendString:tmpLastName];
                [nameStr appendString:@" "];
            }
            if (tmpFirstName)
            {
                [nameStr appendString:tmpFirstName];
            }
        }
        else
        {
            if (tmpFirstName)
            {
                [nameStr appendString:tmpFirstName];
                [nameStr appendString:@" "];
            }
            if (tmpLastName)
            {
                [nameStr appendString:tmpLastName];
                
            }
        }
        [peopleDict setValue:nameStr forKey:addressNameKey];
        
        
        //获取的联系人单一属性:Generic phone number
        ABMultiValueRef phone = ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonPhoneProperty);
        NSMutableArray *phoneNumberArr = [NSMutableArray arrayWithCapacity:0];
        
        for(NSInteger j = 0; j < ABMultiValueGetCount(phone); j++)
            
        {
            NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, j);
            [phoneNumberArr addObject:[NSString stringWithFormat:@"%@",personPhone]];
        }
        [peopleDict setValue:phoneNumberArr forKey:@"phoneNumberArr"];
        [_iphoneList addObject:peopleDict];
        CFRelease(tmpPerson);
//        CFRelease(tmpAddressBook);
    }
    [_addressTable reloadData];
}

#pragma mark - UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _iphoneList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identify = @"addressCell";
    BanBu_addTongxunluCell * cell = (BanBu_addTongxunluCell *)[tableView dequeueReusableCellWithIdentifier:identify];
    if (!cell)
    {
        cell = [[[BanBu_addTongxunluCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify]autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSDictionary * peopleDict = [_iphoneList objectAtIndex:indexPath.row];
    cell.textLabel.text = [peopleDict valueForKey:addressNameKey];
    __block id bself = self;
    __block NSDictionary * bpeopleDict = peopleDict;
    
    [cell setPressedBuCallBack:^{
        [bself cellPressedCallBack:bpeopleDict];
    }];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 47;
}

#pragma mark - 发送信息邀请好友
- (void)cellPressedCallBack:(NSDictionary *)peopleDict
{
    NSString * shareUrl;
    if ([UserDefaults valueForKey:@"user_shortUrl"])
    {
        shareUrl = (NSString *)[UserDefaults valueForKey:@"user_shortUrl"];
    }
    else
    {
        shareUrl = [NSString stringWithFormat:@"http://www.halfarea.com/shareto/userview.html?userid=%@",MyAppDataManager.useruid];
    }
    NSString * message = [NSString stringWithFormat:@"%@ %@。%@ %@",NSLocalizedString(@"invite_pre", nil),MyAppDataManager.useruid,NSLocalizedString(@"koochatComment", nil),shareUrl];

//    NSString* message = [NSString stringWithFormat:@"%@http://www.halfarea.com/dl/",NSLocalizedString(@"inviteFriend", nil)];
    NSString* number = @"";
    MFMessageComposeViewController* controller = [[MFMessageComposeViewController alloc] init];
    if ([MFMessageComposeViewController canSendText])
    {
        controller.body =  message;
        //parse through receipients
        NSScanner* numberScanner = [NSScanner scannerWithString:number];
        [numberScanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@","]];
        NSCharacterSet* charactersToSkip = [NSCharacterSet characterSetWithCharactersInString:@","];
        NSString* substring = @"";
        NSMutableArray *substrings = [NSMutableArray array];
        while (![numberScanner isAtEnd]) {
            [numberScanner scanUpToCharactersFromSet:charactersToSkip intoString:&substring];
            [numberScanner scanCharactersFromSet:charactersToSkip intoString:NULL];
            NSLog(@"%@", substring);
            [substrings addObject:substring];
        }
        controller.recipients = [NSArray arrayWithObject:[peopleDict[@"phoneNumberArr"] objectAtIndex:0]];
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:nil];
    }
}




-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
    if(result == MessageComposeResultCancelled)
        
        
        if (result == MessageComposeResultCancelled)
        {
            NSLog(@"Message cancelled");
        }
        else if (result == MessageComposeResultSent)
        {
            NSLog(@"Message sent");
        }
        else
        {
            NSLog(@"Message failed");
        }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
